<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">登录网格化管理系统</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form ref="loginRef" :model="loginForm" class="login-form" layout="vertical" @submit="handleSubmit">
      <a-form-item
          field="username"
          :rules="[{ required: true, message: '用户名不能为空' }]"
          :validate-trigger="['change', 'blur']"
          hide-label
      >
        <a-input v-model="loginForm.username" placeholder= "用户名">
          <template #prefix>
            <icon-user/>
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
          field="password"
          :rules="[{ required: true, message: '密码不能为空' }]"
          :validate-trigger="['change', 'blur']"
          hide-label
      >
        <a-input-password
            v-model="loginForm.password"
            placeholder="密码"
            allow-clear
        >
          <template #prefix>
            <icon-lock/>
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item
          field="code"
          :rules="[{ required: true, message: '验证码不能为空' }]"
          :validate-trigger="['change', 'blur']"
          hide-label
      >
        <a-input
            v-model="loginForm.code"
            style="width: 63%"
            placeholder="验证码"
            allow-clear
        >
          <template #prefix>
            <icon-safe/>
          </template>
        </a-input>
        <div class="login-code">
          <img @click="getCode" :src="codeUrl" class="login-code-img"/>
        </div>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
              checked="rememberPassword"
              v-model="loginForm.rememberMe"
              @change="setRememberPassword"
          >
            记住密码
          </a-checkbox>
          <a-link @click="$emit('passpwd',true)">忘记密码</a-link>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading">
          登录
        </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import {ref} from "vue";

const userStore = useUserStore()
const router = useRouter();
const { proxy } = getCurrentInstance();
const errorMessage = ref('');

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: true,
  code: "",
  uuid: "",
});

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaOnOff = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

const setRememberPassword = (value) => {
  loginForm.value.rememberMe = value;
};

const handleSubmit = async ({errors,values}) => {
  if (!errors) {
    loading.value = true;
    // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
    if (loginForm.value.rememberMe) {
      Cookies.set("username", loginForm.value.username, { expires: 30});
      Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30});
    } else {
      // 否则移除
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove("rememberMe");
    }
    // 调用action的登录方法
    userStore.login(loginForm.value).then(() => {
      router.push({ path: redirect.value || "/" });
    }).catch(() => {
      loading.value = false;
      loginForm.value.code = ''
      // 重新获取验证码
      if (captchaOnOff.value) {
        getCode();
      }
    });
  }
};

function getCode() {
  getCodeImg().then(res => {
    captchaOnOff.value = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    if (captchaOnOff.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

getCode();
getCookie();
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }

  .login-code {
    width: 37%;
    height: 36px;
    float: right;
    padding-left: 30px;
    padding-top: 2px;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .login-code-img {
    height: 32px;
  }
}
</style>

